package juc.cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/*
* 那些并发包下的cas操作类底层都是用到unsafe类下的底层方法
* 目的:测试使用unsafe完成共享资源的保护
* */
public class UnsafeCas {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        /*通过反射获得unsafe类*/
        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        Unsafe unsafe =(Unsafe) unsafeField.get(null);

        /*获取user中 name age 字段的偏移量*/
        long nameOffset = unsafe.objectFieldOffset(User.class.getDeclaredField("name"));
        System.out.println("name偏移量"+nameOffset);
        long ageOffset = unsafe.objectFieldOffset(User.class.getDeclaredField("age"));
        System.out.println("age偏移量"+ageOffset);
        User user = new User();
        unsafe.compareAndSwapObject(user,nameOffset,user.getName(),"zs");
        unsafe.compareAndSwapInt(user,ageOffset,user.getAge(),18);
        System.out.println(user);
    }
    static class User{
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
